//
//  BankMapViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/21.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import MapKit

class BankMapViewController: KMViewController {

    fileprivate var startLatitude:CGFloat = 0 //起点经度
    fileprivate var startLongitude:CGFloat = 0 //起点纬度
    fileprivate var travelType = driving //出行方式

    
    fileprivate var polyline : MAPolyline! //路线折线
    fileprivate var mapView : MAMapView! //地图
    fileprivate let search = AMapSearchAPI() //搜索
    
    var naviRoute : MANaviRoute?
    var route: AMapRoute?
    
    var currentSearchType = AMapRoutePlanningType.drive
    
    var model : BankDetailsModel!
    
    
    //起点经纬度
    var startCoordinate : CLLocationCoordinate2D!
    //终点经纬度
    var destinationCoordinate : CLLocationCoordinate2D!
    
    
    init(startLatitude:CGFloat,startLongitude:CGFloat,model:BankDetailsModel) {
        super.init(nibName: nil, bundle: nil)
        
        self.startLatitude = startLatitude
        self.startLongitude = startLongitude
        self.model = model
        
        //起点经纬度
        startCoordinate = CLLocationCoordinate2DMake(CLLocationDegrees(self.startLatitude), CLLocationDegrees(self.startLongitude))
        //终点经纬度
        destinationCoordinate = CLLocationCoordinate2DMake(CLLocationDegrees(model.latitude!), CLLocationDegrees(model.longitude!))
        
        }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = routePlanning
        
        
        showMAp()
        createSubView()
        drivePlanning()
    }
    
    //MARK: 创建子视图
    fileprivate func createSubView() {
        
        let headView = MapHeadView()
        headView.mapDelegate = self
        self.view.addSubview(headView)
        
        let navigationBtn = UIButton()
        navigationBtn.setTitle(startNavigation, for: .normal)
        navigationBtn.setTitleColor(UIColor.black, for: .normal)
        navigationBtn.backgroundColor = UIColor.mineColor()
        navigationBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        navigationBtn.addTarget(self, action: #selector(openSystemMap), for: .touchUpInside)
        self.view.addSubview(navigationBtn)
        
        headView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 60))
        }
        
        navigationBtn.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom).offset(RATIO_H(maxNum: 20))
            make.right.equalTo(-10)
            make.width.equalTo(ScreenW/5)
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
    }
    
    //MARK: 打开系统第三方导航应用程序
    @objc fileprivate func openSystemMap() {
        
        KMTool.setBottomAlertView(title: selectOpenMap, msg: nil, target: self, actionTitle: [gaodeMap,baiduMap,iPhoneMap]) {[weak self] (alert) in
            
            switch alert.title {
            case gaodeMap: //高德地图
                
                    var string = "iosamap://navi?sourceApplication= &backScheme= &lat=\(self?.destinationCoordinate.latitude ?? 0)&lon=\(self?.destinationCoordinate.longitude ??  0)&dev=0&style=2"
                    string = string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
                    UIApplication.shared.openURL(URL(string: string)!)

            case baiduMap: //百度地图

                var string = "baidumap://map/direction?origin={{我的位置}}&destination=latlng:\(self?.destinationCoordinate.latitude ?? 0),\(self?.destinationCoordinate.longitude ?? 0)|name=目的地&mode=driving&coord_type=gcj02"
                string = string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
                UIApplication.shared.openURL(URL(string: string)!)

            case iPhoneMap: //苹果地图
                
                let currentLocation = MKMapItem.forCurrentLocation()
                let tolocation = MKMapItem.init(placemark: MKPlacemark.init(coordinate: (self?.destinationCoordinate)!, addressDictionary: nil))
                tolocation.name = (self?.model.name)!
                MKMapItem.openMaps(with: [currentLocation,tolocation], launchOptions: [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:true])
            
                break
                
            default:
                break
            }
        }
    }
    
    //MARK: 加载地图
    fileprivate func showMAp() {
        
        mapView = MAMapView.init(frame: self.view.bounds)
        mapView.delegate = self
        mapView.showsUserLocation = true //定位到当前位置
        mapView.userTrackingMode = .follow //显示当前位置标记
        mapView.showsCompass = false //不显示指南针

        self.view.addSubview(mapView)
        
        //定位当前位置蓝点
        let userLocation = MAUserLocationRepresentation()
        //定位点背景颜色
        userLocation.locationDotBgColor = UIColor.clear
        //不显示动画
        userLocation.enablePulseAnnimation = false
        //起点标记图片
        userLocation.image = UIImage()
        //刷新
        mapView.update(userLocation)
        
        addAnnotation()
        self.search?.delegate = self
    }
    
    //MARK: 驾车路线规划
    fileprivate func drivePlanning() {
        
        let request = AMapDrivingRouteSearchRequest()
        request.origin = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
        request.destination = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
        request.requireExtension = true
        
        self.search?.aMapDrivingRouteSearch(request)
        
        
    }
    
    //MARK: 步行路线规划
    fileprivate func walkPlanning() {
        
        let requset = AMapWalkingRouteSearchRequest()
        requset.origin = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
        requset.destination = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
        
        self.search?.aMapWalkingRouteSearch(requset)
        
    }
    
    //MARK: 公交路线规划
    fileprivate func busPlanning() {
        
        let request = AMapTransitRouteSearchRequest()
        request.origin = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
        request.destination = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
        request.requireExtension = true
        request.city = model.city
        
        self.search?.aMapTransitRouteSearch(request)
    }
    
    //MARK: 骑行路线规划
    fileprivate func ridePlanning() {
        
        let requset = AMapRidingRouteSearchRequest()
        requset.origin = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
        requset.destination = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
        
        self.search?.aMapRidingRouteSearch(requset)
    }
    
    //MARK: 出行路线
    fileprivate func travelRoute() {
        
        //根据坐标点绘线
//        var lineCoordinates = [CLLocationCoordinate2D]()
//        let steps = (paths.first?.steps)!
//        for i in 0..<steps.count {
//
//            let step = steps[i]
//            let polylines = step.polyline.components(separatedBy: ";")
//            for polyline in polylines {
//                let point = polyline.components(separatedBy: ",")
//                let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(point[1])!, CLLocationDegrees(point[0])!)
//                lineCoordinates.append(coordinate)
//            }
//        }
//
//        polyline = MAPolyline(coordinates: &lineCoordinates, count: UInt(lineCoordinates.count))
//        mapView.add(polyline)
        
        let start = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
        let end = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
        
        if self.currentSearchType == .bus {
            if route?.transits == nil {
                return
            }
            naviRoute = MANaviRoute(for: route?.transits.first, start: start, end: end)
        }else{
            if route?.paths == nil {
                return
            }
            naviRoute = MANaviRoute(for: route?.paths.first, withNaviType: MANaviAnnotationType(rawValue: currentSearchType.rawValue)!, showTraffic: true, start: start, end: end)
        }
        
        naviRoute?.add(to: mapView)
        
        mapView.showOverlays(naviRoute?.routePolylines, edgePadding: .init(top: 20, left: 20, bottom: 20, right: 20), animated: true)
    }
    
   

    
    //MARK: 添加大头针
    fileprivate func addAnnotation() {
        
        let anno = MAPointAnnotation()
        anno.coordinate = startCoordinate
        anno.title = "start"
        
        mapView.addAnnotation(anno)
        
        let annod = MAPointAnnotation()
        annod.coordinate = destinationCoordinate
        annod.title = model.name
        annod.subtitle = (model.address ?? "") + "\n" + (model.tel ?? "")
        
        mapView.addAnnotation(annod)
        
        //显示终点信息
        mapView.selectAnnotation(annod, animated: true)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

        

    }

}

extension BankMapViewController : MAMapViewDelegate,AMapSearchDelegate {
    
    //MARK: 路线搜索成功
    func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) {
        
        mapView.removeAnnotations(mapView.annotations)
        mapView.removeOverlays(mapView.overlays)
        
        addAnnotation()
        
        if response.route == nil {
            KMTool.showText(_text: notAboutNews)
            return
        }
        
        self.route = nil
        if response.count > 0 {
            self.route = response.route
            self.travelRoute()
        }
        
    }
    
    //MARK: 路线搜索失败
    func mapViewDidFailLoadingMap(_ mapView: MAMapView!, withError error: Error!) {
        
        KMTool.showText(_text: error.localizedDescription)
    }
    
    //MARK: 设置折线样式
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        if overlay.isKind(of: LineDashPolyline.self) {
            let naviPolyline: LineDashPolyline = overlay as! LineDashPolyline
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: naviPolyline.polyline)
            renderer.lineWidth = 5.0
            renderer.strokeColor = UIColor.red
            renderer.lineDashType = MALineDashType.square
            
            return renderer
        }
        if overlay.isKind(of: MANaviPolyline.self) {
            
            let naviPolyline: MANaviPolyline = overlay as! MANaviPolyline
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: naviPolyline.polyline)
            renderer.lineWidth = 5.0
            
            if naviPolyline.type == MANaviAnnotationType.walking {
                renderer.strokeColor = naviRoute?.walkingColor
            }
            else if naviPolyline.type == MANaviAnnotationType.railway {
                renderer.strokeColor = naviRoute?.railwayColor;
            }
            else {
                renderer.strokeColor = naviRoute?.routeColor;
            }
            
            return renderer
        }
        if overlay.isKind(of: MAMultiPolyline.self) {
            let renderer: MAMultiColoredPolylineRenderer = MAMultiColoredPolylineRenderer(multiPolyline: overlay as! MAMultiPolyline?)
            renderer.lineWidth = 5.0
            renderer.strokeColors = naviRoute?.multiPolylineColors
            
            return renderer
        }
        
        return nil
    }
    
    //MARK: 添加大头针
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation.isKind(of: MAUserLocation.self) {
            return nil
        }
        
        if annotation.isKind(of: MAPointAnnotation.self) {
            let pointReuseIndetifier = "pointReuseIndetifier"
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
                annotationView!.canShowCallout = true
                annotationView!.isDraggable = false
            }
            
            annotationView!.image = nil
            
            if annotation.isKind(of: MANaviAnnotation.self) {
                let naviAnno = annotation as! MANaviAnnotation
                
                switch naviAnno.type {
                case MANaviAnnotationType.railway:
                    annotationView!.image = UIImage(named: "railway_station")
                    break
                case MANaviAnnotationType.drive:
                    annotationView!.image = UIImage(named: "car")
                    break
                case MANaviAnnotationType.riding:
                    annotationView!.image = UIImage(named: "ride")
                    break
                case MANaviAnnotationType.walking:
                    annotationView!.image = UIImage(named: "man")
                    break
                case MANaviAnnotationType.bus:
                    annotationView!.image = UIImage(named: "bus")
                    break
                case .truck:
                    annotationView!.image = UIImage(named: "truck")
                    break
                }
            }
            else {
                if annotation.title == "start" {
                    annotationView!.image = UIImage(named: "startPoint")
                    annotationView?.isEnabled = false
                }
                else if annotation.title == model.name {
                    annotationView!.image = UIImage(named: "endPoint")
                }
            }
            return annotationView!
        }
        
        return nil
    }
}

extension BankMapViewController : MapHeadViewDelegate {
    
    //MARK: 选择出行方式
    func selectTravel(type: String) {
        
        if type == self.travelType {
            return
        }
        
        self.travelType = type
        
        switch type {
        case driving: //驾车
            self.currentSearchType = .drive
            self.drivePlanning()
        case riding: //骑行
            self.currentSearchType = .riding
            self.ridePlanning()
        case walk: //步行
            self.currentSearchType = .walk
            self.walkPlanning()
        case bus: //公交
            self.currentSearchType = .bus
            self.busPlanning()
        default:
            break
        }
    }
}
